package com.bq.gametrade.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Base64;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bq.gametrade.HttpLink;
import com.bq.gametrade.R;
import com.bq.gametrade.base.BaseActivity;
import com.bq.gametrade.bean.UserInfo;
import com.bq.gametrade.bean.UserInfoDetails;
import com.bq.gametrade.http.VRHttp;
import com.bq.gametrade.http.VRHttpListener;
import com.bq.gametrade.utils.MD5Util;
import com.bq.gametrade.utils.NetworkUtils;
import com.bq.gametrade.utils.PasswordHelp;
import com.bq.gametrade.utils.SharedPreferencesUtils;
import com.bq.gametrade.utils.SystemUtils;

import java.util.HashMap;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;

public class LoginActivity extends BaseActivity implements View.OnClickListener {


    private ImageView back;
    private EditText userName, userPassword;
    private Button btnLogin;
    private TextView tvRegister, tvForgotPassword;
    private ImageView ivWechatLogin, ivAlipayLogin;
    private ImageView btnShowPassword;


    private Activity activity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(R.color.login_bg));

        }
        setContentView(R.layout.activity_login);
        activity = this;
        initView();
        setLoginData();

    }


    private void initView() {

        back = serchViewById(R.id.image_back);
        back.setOnClickListener(this);
        userName = serchViewById(R.id.ed_userAccount);
        userPassword = serchViewById(R.id.ed_userPassword);
        btnLogin = serchViewById(R.id.btn_login);
        btnLogin.setOnClickListener(this);
        tvRegister = serchViewById(R.id.tv_register);
        tvRegister.setOnClickListener(this);
        tvForgotPassword = serchViewById(R.id.tv_forgetPassword);
        tvForgotPassword.setOnClickListener(this);
        ivWechatLogin = serchViewById(R.id.iv_weChat_login);
        ivWechatLogin.setOnClickListener(this);
        ivAlipayLogin = serchViewById(R.id.iv_alipay_login);
        ivAlipayLogin.setOnClickListener(this);

        btnShowPassword = serchViewById(R.id.bt_showPassword);
        btnShowPassword.setOnClickListener(this);
    }

    private void setLoginData() {
        String strUserName = (String) SharedPreferencesUtils.getValue(LoginActivity.this, SharedPreferencesUtils.user_account, "");

        String[] loginInfo = PasswordHelp.readPassword(LoginActivity.this);
        if (strUserName != "") {
            userName.setText(loginInfo[0]);
            userPassword.setText(loginInfo[1]);
        }
    }


    private boolean isShow = true;
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.image_back:
                back2Main(false);
                break;
            case R.id.bt_showPassword:
                isShow = !btnShowPassword.isSelected();
                if(isShow){
                    btnShowPassword.setSelected(true);
                    btnShowPassword.setBackgroundResource(R.mipmap.icon_eyes_open);
                    userPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }else {
                    btnShowPassword.setSelected(false);
                    btnShowPassword.setBackgroundResource(R.mipmap.icon_eyes_close);
                    userPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }

                break;
            case R.id.btn_login:
                if (TextUtils.isEmpty(userName.getText().toString())) {
                    toastShow("您还没有输入账号");
                    return;
                }
                if (TextUtils.isEmpty(userPassword.getText().toString())) {
                    toastShow("您还没有输入密码");
                    return;
                }
                if (NetworkUtils.isNetworkAvailable(LoginActivity.this)) {
                    userToLogin();
                } else {
                    toastShow("请连接网络");
                }
                break;
            case R.id.tv_register:
                startActivity(new Intent(LoginActivity.this, RegisteredActivity.class));
                break;
            case R.id.tv_forgetPassword:
                startActivity(new Intent(LoginActivity.this, RetrievePasswordActivity.class));
                break;
            case R.id.iv_weChat_login:
                Toast.makeText(LoginActivity.this, "正在登录····", Toast.LENGTH_LONG).show();
                weChatLogin();
                break;
            case R.id.iv_alipay_login:
                break;

        }
    }

    /**
     * 发起微信授权登录
     */
    private void weChatLogin() {
//        application.iwxapi = WXAPIFactory.createWXAPI(LoginActivity.this, application.WX_APP_ID);
//        application.iwxapi.registerApp(application.WX_APP_ID);
//        SendAuth.Req req = new SendAuth.Req();
//        req.scope = "snsapi_userinfo";
//        req.state = "BQTrading";
//        application.iwxapi.sendReq(req);
    }

    private void userToLogin() {
        /**
         * loginType=wx  微信登录
         *loginType=ali 支付宝 （预留）
         *loginType=0   普通登录
         */

        final String myPassword = MD5Util.md5(userPassword.getText().toString());
        Map<String, String> params = new HashMap<>();

        params.put("username", userName.getText().toString());
        params.put("password", myPassword);
        params.put("loginType", "0");
        params.put("deviceType", "1");
        params.put("deviceId", JPushInterface.getRegistrationID(LoginActivity.this));
        showSpotsDialog();
        VRHttp.userToLogin(activity, HttpLink.LOGIN_URL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                closeSpotsDialog();
                UserInfo userInfo = (UserInfo) response;
                if (userInfo.status.equals("0")) {
                    UserInfoDetails userInfoDetails = userInfo.userinfo;
                    application.setUserInfo(userInfoDetails);
                    SharedPreferencesUtils.saveValue(LoginActivity.this, SharedPreferencesUtils.user_account, userName.getText().toString());
                    SharedPreferencesUtils.saveValue(LoginActivity.this, SharedPreferencesUtils.user_passwor, myPassword);
                    PasswordHelp.savePassword(LoginActivity.this, userName.getText().toString(), userPassword.getText().toString(), true);
                    back2Main(true);
                } else {
                    toastShow(new String(Base64.decode(userInfo.message.getBytes(), 0, userInfo.message.length(), Base64.DEFAULT)));
                }
            }

            @Override
            public void onError(String error) {
                super.onError(error);
                closeSpotsDialog();
                toastShow("登录失败");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeSpotsDialog();

            }
        });
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            back2Main(false);
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void back2Main(boolean islogined) {

        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        intent.putExtra("isLogin", islogined);
        startActivity(intent);
        finish();
        overridePendingTransition(R.anim.r2l_in, R.anim.r2l_out);

    }
}
